package cn.itcast.p2p20.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;

import java.io.IOException;
import java.io.Reader;

import cn.itcast.p2p20.bean.request.QueryRequest;
import cn.itcast.p2p20.safe.AsymmetricPublicAlgorithm;
import cn.itcast.p2p20.safe.SafetyUtil;

/**
 * Created by Administrator on 2016/7/24.
 */
public class NetUtil {

    private static ConnectivityManager mConnectivityManager;

    public static void init(Context context) {

        mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public static<Res extends BaseReponse> void sendRequest(BaseRequest request, Class<Res> responseClass, Callback callback) {

        //请求之前应该判断网络
        if (checkNet()) {

            new NetTask().execute(new NetBean(request, responseClass, callback));

        } else {

            callback.onError(request, new IllegalStateException("请检查网络连接"));
        }
    }

    private static class NetBean {

        public NetBean(BaseRequest request, Class<? extends BaseReponse> responseClass, Callback callback) {
            this.request = request;
            this.responseClass = responseClass;
            this.callback = callback;
        }

        BaseRequest request;
        Callback callback;
        //响应结果对象的字节码
        Class<? extends BaseReponse> responseClass;

        //响应封装的对象
        BaseReponse baseReponse;
        //异常信息
        Exception exception;
    }

    //需要拿到Resuest,Callback
    private static class NetTask extends AsyncTask<NetBean, Void, NetBean> {

        @Override
        protected NetBean doInBackground(NetBean... params) {

            NetBean netBean = params[0];
            //执行网络请求
            try {

                //响应的请求来自于数据安全查询，需要对返回的json数据进行解密
                if (netBean.request instanceof QueryRequest) {

                    //加密的字符串
                    String stringResponse = HttpWrapper.getInstance().getStringResponse(netBean.request);
//                    String sign = SafetyUtil.encrypt(AsymmetricPrivateAlgorithm.RSA,
//                            resJson, SafetyUtil.getPriKey());

                    stringResponse = SafetyUtil.decrypt(AsymmetricPublicAlgorithm.RSA,
                            stringResponse, SafetyUtil.getPubKey());

                    BaseReponse baseReponse = new Gson().fromJson(stringResponse, netBean.responseClass);
                    netBean.baseReponse = baseReponse;

                } else {

                    Reader readerResponse = HttpWrapper.getInstance().getReaderResponse(netBean.request);
                    BaseReponse baseReponse = new Gson().fromJson(readerResponse, netBean.responseClass);
                    netBean.baseReponse = baseReponse;
                }

            } catch (IOException e) {
                e.printStackTrace();
                netBean.exception = e;
            } catch (JsonParseException e) {
                e.printStackTrace();
                netBean.exception = e;
            } catch (Exception e) {
                e.printStackTrace();
                netBean.exception = e;
            }
            return netBean;
        }

        //在主线程回调调用者的Callback对象
        @Override
        protected void onPostExecute(NetBean netBean) {

            if (netBean.exception != null) {

                netBean.callback.onError(netBean.request, netBean.exception);
            } else {

                if (netBean.baseReponse != null && netBean.baseReponse.success()) {

                    netBean.callback.onSuccess(netBean.request, netBean.baseReponse);
                } else {

                    netBean.callback.onOther(netBean.request, netBean.baseReponse);
                }

            }

        }
    }


    private static boolean checkNet() {

        NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
    }


}
